package mem

import (
	"cowb/log"
	"time"

	"github.com/garyburd/redigo/redis"
)

var pool *redis.Pool

type RedisConf struct {
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
	Mode        bool
	PassWord    string
	Path        string
}

func InitRedisPool(conf RedisConf) *redis.Pool {
	if pool != nil {
		return pool
	}

	pool = &redis.Pool{
		MaxIdle:     conf.MaxIdle,
		MaxActive:   conf.MaxActive,
		IdleTimeout: conf.IdleTimeout,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", conf.Path)
			if err != nil {
				log.Fatal("Redis Can't Connect: %v", err)
			}
			if conf.Mode {
				if _, err := c.Do("AUTH", conf.PassWord); err != nil {
					log.Fatal("Redis Can't Connect: %v", err)
				}
			}
			return c, nil
		},
	}

	return pool
}

func InitRedisPoolDefault(host string) *redis.Pool {
	return InitRedisPool(RedisConf{MaxIdle: 5, MaxActive: 500, IdleTimeout: time.Second * 300, Path: host, Mode: false})
}

func Do(cmd string, args ...interface{}) (interface{}, error) {
	rc := pool.Get()
	defer rc.Close()
	return rc.Do(cmd, args...)
}
